#include  <config.h>
#include  <core.h>

static pthread_key_t key;

//mem pool for per thread
static pool_t **pools;
static int pool_num;

// MUST be called firstly
int thread_key_create(void (*destructor)(void*))
{
    return pthread_key_create(&key,destructor);    
}

int thread_setspecific(void *opaque)
{
    return pthread_setspecific(key, opaque);
}

void thread_init_pools(int threads, int size)
{
    int i;

    pools = malloc(sizeof(pool_t*)*threads);
    pool_num = threads;
    for(i=0;i<threads;i++){
       pools[i] = create_pool(size);
       printf("pools[%d]:%p:%p\n",i,pools[i],&pools[i]);
    }
}



void destroy_pools()
{
  if(pools){
    int i;
    for(i=0;i<pool_num;i++){
       pool_t *p = pools[i];
       destroy_pool(p);
    }
    free(pools);
  }
}

pool_t * thread_mem_pool()
{
    void *ret;
    int idx = 0;
    if((ret=pthread_getspecific(key)) != NULL)
      idx = *(int*)ret;
    printf("thread_mem_pool pools:%d \n",idx);
    return pools[idx];
}

void thread_destroy_pools()
{
	pool_t *pool = thread_mem_pool();
	if(!pool) return;
	destroy_pool(pool);
}

void * thread_calloc(size_t size)
{
    pool_t *pool = thread_mem_pool();
    if(!pool) return NULL;
    return pool_calloc(pool,size);
}

void *thread_realloc(void *data,size_t osize,size_t size)
{
    pool_t *pool = thread_mem_pool();
    if(!pool) return NULL;
    printf("pool max:%zd\n",pool->max);
    return pool_realloc(pool,data,osize,size);
}

void thread_reset_pool()
{
    pool_t *pool = thread_mem_pool();
    if(!pool) return ;
    reset_pool(pool);
}

unsigned int thread_recycle(void *pdata,size_t size)
{
    pool_t *pool = thread_mem_pool();
    if(!pool) return 1;
    return pool_recycle(pool,pdata,size);
}

unsigned int thread_free(void *pdata,size_t size)
{
    pool_t *pool = thread_mem_pool();
    if(!pool) return 1;
    return pool_free(pool,pdata,size);
}
